﻿

Public Class Passwords

    Public VersionPasswordSafe As Integer = 5
    Dim Messages As String()
    Dim Headers As String()
    Dim MessageType As String()

    Dim NumberOfMessages As Integer = 0

    Protected Overrides Sub OnResize(ByVal e As System.EventArgs)
        MyBase.OnResize(e)
        Select Case Me.WindowState
            Case FormWindowState.Normal
                'MessageBox.Show("Form was restored", Application.ProductName)
                Me.ShowInTaskbar = True
            Case FormWindowState.Minimized
                'MessageBox.Show("Form was minimized", Application.ProductName)
                If Me.ChkBoxAutoLockMinimise.Checked Then
                    Call LockScreen()
                End If
                Me.ShowInTaskbar = False
                Me.NotifyIcon1.BalloonTipText = "Formition Password Safe can be found here."
                Me.NotifyIcon1.ShowBalloonTip(2000)
            Case FormWindowState.Maximized
                'MessageBox.Show("Form was maximized", Application.ProductName)
                Me.ShowInTaskbar = True
        End Select
    End Sub

    Public Sub CheckRegistration()

        If Common.RegisterLater = True Then
            Exit Sub
        End If

        'here we ensure the user has paid for the software
        If Common.ValidateRegistration() Then
            'do nothing....
        Else
            Registration.Visible = True
            Registration.Enabled = True
            Me.Enabled = False
            Common.BackgroundDataLoadingIgnoreEvents = True
            Me.Close()
            Common.BackgroundDataLoadingIgnoreEvents = False
        End If
    End Sub

    Public Sub UpgradeSoftwareVersion()

        Me.Cursor = Cursors.WaitCursor

        Try


            'check for new version
            'we need to know where the database is currently stored (use Registry)
            'we need to know where the EXE is currently installed (use Registry)
            'need to accept that there may not be internet connectivity
            'need to not both the user everytime, maybe avoid popups, have a link on the main screen...
            Dim y As New Formition.FormitionPasswordSafe
            If Not TestMode Then
                y.Url = "http://www.formition.com/desktopmodules/formition/formitionpasswordsafe.asmx"
                y.Credentials = System.Net.CredentialCache.DefaultCredentials
                y.Proxy = System.Net.WebProxy.GetDefaultProxy
                y.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials
                System.Net.ServicePointManager.Expect100Continue = False
            End If

            Dim CurrentVersion As String


            CurrentVersion = y.Version

            Me.Cursor = Cursors.Default

            If CurrentVersion > VersionPasswordSafe Then

                Dim Upgrade As String = MsgBox("A newer version (v" & CurrentVersion & ") is available to install, would you like to download and install this now?", MsgBoxStyle.OkCancel, "Formition Password Safe")
                If Upgrade = 1 Then
                    Dim rc As String
                    rc = Shell(Microsoft.Win32.Registry.GetValue("HKEY_CURRENT_USER\Formition", "ApplicationRunningPath", "") & "\upgrade.exe", vbNormalFocus)
                    'upgrade launched, now close this exe
                    'The upgrade.exe will download the new form and then reload it.
                    'ya man!
                    Common.BackgroundDataLoadingIgnoreEvents = True
                    Me.Close()
                End If
            Else
                Me.Cursor = Cursors.Default
                Call Me.Message("Upgrade Check", "You have the latest version, no upgrades available.", "Info")
            End If


        Catch ex As Exception
            Me.Cursor = Cursors.Default
            Call Message("Website Unavailable", "The website is currently unavailable; if you experience difficulties please contact us through the formition website. " & ex.Message)
        End Try
    End Sub


   

    Private Sub CheckNewInstallation()

        
        'Here we want check if there is a database located in this users application folder.
        'if there is not we want to copy the database from the installation folder to the users database.
        'This creates some problems, in that users cannot share databases in the sense so 
        'if anything a parent can't backup another persons password list.
        'but at the same time nobody else can get access to their password data unless they
        'are an administrator.

        Dim DatabasePath As String = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) & "\Formition\Password Safe\Database\"
        Dim ApplicationPath As String = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) & "\Formition\Password Safe\"

            If Not FileIO.FileSystem.DirectoryExists(DatabasePath) Then
                'create the folder
                FileIO.FileSystem.CreateDirectory(DatabasePath)
            End If

        If Not FileIO.FileSystem.FileExists(DatabasePath & "PasswordCache.sdf") Then

            'We have a new user installing this. Record the initial installation location
            Call Microsoft.Win32.Registry.SetValue("HKEY_CURRENT_USER\Formition", "ApplicationInstallPath", Application.StartupPath.ToString)

            'copy files required to the data folder, we assume this is a clean install.
            FileIO.FileSystem.CopyFile(Application.StartupPath & "\InstallFiles\PasswordCache.sdf", DatabasePath & "PasswordCache.sdf", True)
            FileIO.FileSystem.CopyFile(Application.StartupPath & "\Password Safe.exe", ApplicationPath & "Password Safe.exe", True)
            FileIO.FileSystem.CopyFile(Application.StartupPath & "\Password Safe.exe.config", ApplicationPath & "Password Safe.exe.config", True)

         
            FileIO.FileSystem.CopyFile(Application.StartupPath & "\FormitionControls.dll", ApplicationPath & "FormitionControls.dll", True)
            FileIO.FileSystem.CopyFile(Application.StartupPath & "\InstallFiles\Upgrade.exe", ApplicationPath & "Upgrade.exe", True)
            'FileIO.FileSystem.CopyFile(Application.StartupPath & "\InstallFiles\Register.exe", ApplicationPath & "Register.exe", True)

            FileIO.FileSystem.CopyFile(Application.StartupPath & "\Microsoft.VisualBasic.PowerPacks.Vs.dll", ApplicationPath & "Microsoft.VisualBasic.PowerPacks.Vs.dll", True)
            FileIO.FileSystem.CopyFile(Application.StartupPath & "\sqlcecompact35.dll", ApplicationPath & "sqlcecompact35.dll", True)
            FileIO.FileSystem.CopyFile(Application.StartupPath & "\sqlceme35.dll", ApplicationPath & "sqlceme35.dll", True)
            FileIO.FileSystem.CopyFile(Application.StartupPath & "\sqlceqp35.dll", ApplicationPath & "sqlceqp35.dll", True)
            FileIO.FileSystem.CopyFile(Application.StartupPath & "\sqlcese35.dll", ApplicationPath & "sqlcese35.dll", True)
            FileIO.FileSystem.CopyFile(Application.StartupPath & "\System.Data.SqlServerCe.dll", ApplicationPath & "System.Data.SqlServerCe.dll", True)
            FileIO.FileSystem.CopyFile(Application.StartupPath & "\System.Data.SqlServerCe.Entity.dll", ApplicationPath & "System.Data.SqlServerCe.Entity.dll", True)




        End If

        Common.ConnectionString = "Data Source=" & DatabasePath & "PasswordCache.sdf;"
        Common.DatabasePath = DatabasePath


        'If this EXE was kicked off from Program Files, we actually want to close down and run 
        'a new instance of this program from data files folder.
        'This is because if we upgrade in the future any user is allowed to 
        'modify their data folder, but not the program files folder. So we just run this out of
        'the data files folder from the beginning.


     

        If Common.TestMode = False And Application.StartupPath & "\" <> ApplicationPath Then

            Dim Args As String = ""
            Dim ArgArray As String() = Environment.GetCommandLineArgs()
            Dim i As Integer
            If Environment.GetCommandLineArgs.Length > 1 Then
                For i = 2 To Environment.GetCommandLineArgs.Length
                    Args = Args & " " & ArgArray(i - 1)
                Next
            End If

            'open a new instance of this program in this folder
            Dim rc As String
            rc = Shell(ApplicationPath & "Password Safe.exe" & Args, vbNormalFocus)

            'close down this instance of this program.
            'turn this on so it does not ask them to confirm exit.
            Common.BackgroundDataLoadingIgnoreEvents = True
            Me.Close()

        End If

    End Sub

    Private Sub Passwords_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

        If Not Common.BackgroundDataLoadingIgnoreEvents Then


            If MsgBox("Are you sure you want to close this program?", MsgBoxStyle.OkCancel, "Formition Password Safe") = 1 Then

                Common.BackgroundDataLoadingIgnoreEvents = True

                e.Cancel = False
                Try
                    Toolbox.Close()
                Catch ex As Exception
                End Try
                Try
                    Registration.Close()
                Catch ex As Exception
                End Try

                Common.BackgroundDataLoadingIgnoreEvents = False

            Else
                e.Cancel = True
            End If

        End If
    End Sub



    Private Sub Main_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Me.Size = New System.Drawing.Size(473, 538)

        Dim silent As Boolean = False
        'see if this is silent startup
        Dim arguments As [String]() = Environment.GetCommandLineArgs()
        If arguments.Length > 1 Then
            If arguments(1) = "silentstart" Then
                silent = True
            ElseIf arguments(1) = "testmode" Then
                Common.TestMode = True
            End If
        End If

        Call CheckNewInstallation()

        'add catch all error handler
        ' Subscribe to thread (unhandled) exception events
        Dim handler As ThreadExceptionHandler = _
            New ThreadExceptionHandler

        AddHandler Application.ThreadException, _
            AddressOf handler.Application_ThreadException


        'setup the application install path now
        Common.ApplicationInstallPath = Microsoft.Win32.Registry.GetValue("HKEY_CURRENT_USER\Formition", "ApplicationInstallPath", Application.StartupPath.ToString)

        Call SetupScreen("Login")

        If silent Then
             Me.WindowState = FormWindowState.Minimized
        End If


        Call CheckRegistration()

    End Sub


    Public Sub DisableTab(ByVal ObjectControl)
        'recursively disable all tab items on the screen
        'tabbing will be set programatically when the screen loads (as it is easier!)
        Dim SubControl As Windows.Forms.Control
        For Each SubControl In ObjectControl.Controls
            If SubControl.Visible = True Then
                SubControl.TabStop = False
                SubControl.TabIndex = 0
                DisableTab(SubControl)
            End If

            Try
                SubControl.TabIndex = 0
            Catch ex As Exception
                'there is no control called tab index
                Call MsgBox("no tab index on " & SubControl.Name)
            End Try

        Next
    End Sub


    Public Sub HideAllSubForms()


        'Hide All subforms here
        GroupBoxLogin.Visible = False
        GroupBoxRegistration.Visible = False
        GroupPasswordEditor.Visible = False
        GroupBoxSettings.Visible = False
        GroupBoxCategoryEditor.Visible = False
        GroupBoxRestore.Visible = False

    End Sub

    Public Sub DisableAllSubFields()
        If GroupBoxLogin.Visible Then GroupBoxLogin.Enabled = False
        If GroupBoxRegistration.Visible Then GroupBoxRegistration.Enabled = False
        If GroupPasswordEditor.Visible Then GroupPasswordEditor.Enabled = False
        If GroupBoxSettings.Visible Then GroupBoxSettings.Enabled = False
        If GroupBoxCategoryEditor.Visible Then GroupBoxCategoryEditor.Enabled = False
    End Sub

    Public Sub EnableAllSubFields()
        'Enable All subforms here
        If GroupBoxLogin.Visible Then GroupBoxLogin.Enabled = True
        If GroupBoxRegistration.Visible Then GroupBoxRegistration.Enabled = True
        If GroupPasswordEditor.Visible Then GroupPasswordEditor.Enabled = True
        If GroupBoxSettings.Visible Then GroupBoxSettings.Enabled = True
        If GroupBoxCategoryEditor.Visible Then GroupBoxCategoryEditor.Enabled = True
    End Sub
    Public Sub SetupScreen(ByVal ScreenType As String)

        'reset the time out counter as the screen has changed.
        Me.Timer1.Enabled = False
        Me.Timer1.Enabled = True

        Call StatusClear()

        Call HideAllSubForms()



        Select Case ScreenType
            Case "Restore"

                GroupBoxRestore.Visible = True
                GroupBoxRestore.Location = New System.Drawing.Point(0, 0)
                GroupBoxRestore.Size = New Size(473, 528)
                GroupBoxRestore.BringToFront()

                txtRestoreFormitionID.TabStop = True
                txtRestoreUsername.TabStop = True
                txtRestorePassword.TabStop = True
                cmdRestoreSystem.TabStop = True
                cmdRestoreCancel.TabStop = True

                txtRestoreFormitionID.TabIndex = 1
                txtRestoreUsername.TabIndex = 2
                txtRestorePassword.TabIndex = 3
                cmdRestoreSystem.TabIndex = 4
                cmdRestoreCancel.TabIndex = 5

                Me.AcceptButton = cmdRestoreSystem

            Case "Login"

                Try
                    Me.ToolStripComboBox1.Items.Clear()
                    Me.ToolStripComboBox1.Items.Add("Not Logged In")
                    AddNewPasswordToolStripMenuItem.Enabled = False
                    Me.ToolStripComboBox1.SelectedIndex = 0
                Catch ex As Exception

                End Try
          


                'default the master username to the last one used in the register
                Me.txtMasterUsername.Text = Microsoft.Win32.Registry.GetValue("HKEY_CURRENT_USER\Formition", "LastLogonUserName", 0)

                'comment when testing
                'Me.txtMasterPassword.Text = ""

                GroupBoxLogin.Visible = True
                GroupBoxLogin.Location = New System.Drawing.Point(0, 0)
                GroupBoxLogin.Size = New Size(473, 528)
                GroupBoxLogin.BringToFront()

                Call DisableTab(Me)

                txtMasterUsername.TabStop = True
                txtMasterPassword.TabStop = True
                cmdLogin.TabStop = True
                cmdNewUser.TabStop = True
                cmdForgotPassword.TabStop = True

                txtMasterUsername.TabIndex = 5
                txtMasterPassword.TabIndex = 1
                cmdLogin.TabIndex = 2
                cmdNewUser.TabIndex = 3
                cmdForgotPassword.TabIndex = 4

                Me.txtMasterPassword.Focus()

                Me.AcceptButton = Me.cmdLogin




            Case "MainScreen"

                'make sure they have logged in first!!!
                If Common.Userid = Nothing Then
                    Call SetupScreen("Login")
                    Exit Sub
                End If

                'populate categories
                Common.PopulateCategories(CurrentlySelectedUserCategory)
                Common.PopulatePasswordList(CurrentlySelectedUserCategory.ToString)


                'if search has an id in it then launch that
                If Microsoft.VisualBasic.Left(Me.txtSearch.Text.ToString, 3) = "ID:" Then
                    Call Common.LaunchPasswordEditorOnStart(Microsoft.VisualBasic.Right(txtSearch.Text, Len(Me.txtSearch.Text) - 3))
                    Exit Sub
                End If


                'tab key
                'datagrid
                DataGridPasswords.TabIndex = 1
                DataGridPasswords.TabStop = True
                DataGridPasswords.Focus()

                'menu items
                cmdNew.TabStop = True
                cmdDelete.TabStop = True
                cmdCopyUserid.TabStop = True
                cmdCopyPassword.TabStop = True
                cmdLockPasswords.TabStop = True
                cmdLaunchWeblink.TabStop = True
                cmdSettings.TabStop = True

                cmdNew.TabIndex = 2
                cmdDelete.TabIndex = 3
                cmdCopyUserid.TabIndex = 4
                cmdCopyPassword.TabIndex = 5
                cmdLockPasswords.TabIndex = 6
                cmdLaunchWeblink.TabIndex = 7
                cmdSettings.TabIndex = 8



                'other
                cboCategory.TabStop = True
                cmdCategoryEditor.TabStop = True
                txtSearch.TabStop = True
                cmdSearchGo.TabStop = True

                cboCategory.TabIndex = 9
                cmdCategoryEditor.TabIndex = 10
                txtSearch.TabIndex = 11
                cmdSearchGo.TabIndex = 12

                'setup default enter button
                Me.AcceptButton = cmdSearchGo

            Case "Registration"

                'form visibility
                GroupBoxRegistration.Location = New System.Drawing.Point(0, 0)
                GroupBoxRegistration.Visible = True
                GroupBoxRegistration.BringToFront()
                GroupBoxRegistration.Size = New Size(473, 528)
                GroupBoxRegistration.Enabled = True

                'turn tab stop off for everything visible
                Call DisableTab(Me)

                'tab key
                txtNewUsername.TabIndex = 0
                txtNewUsername.Focus()
                txtNewUsername.TabStop = True
                txtNewPassword1.TabIndex = 1
                txtNewPassword1.TabStop = True
                txtNewPassword2.TabIndex = 2
                txtNewPassword2.TabStop = True
                txtPasswordReminder.TabStop = True
                txtPasswordReminder.TabIndex = 3
                cmdRegister.TabIndex = 4
                cmdRegister.TabStop = True
                cmdRegistrationCancel.TabIndex = 5
                cmdRegistrationCancel.TabStop = True

                'setup default enter button
                Me.AcceptButton = Me.cmdRegister

            Case "Editor"

                Call SomethingChanged()

                'form visibility
                GroupPasswordEditor.Location = New System.Drawing.Point(0, 0)
                GroupPasswordEditor.Visible = True
                GroupPasswordEditor.BringToFront()
                GroupPasswordEditor.Size = New Size(473, 528)
                GroupPasswordEditor.Enabled = True
                'turn tab stop off for everything visible

                Call DisableTab(Me)

                'tab key
                cboEditorCategory.TabStop = True
                txtEditorName.TabStop = True
                txtEditorWebsite.TabStop = True
                txtEditorDescription.TabStop = True
                txtEditorUsername.TabStop = True
                txtEditorPassword.TabStop = True
                txtEditorConfirmPassword.TabStop = True

                cmdEditorCancel.TabStop = True
                cmdEditorSave.TabStop = True



                cboEditorCategory.TabIndex = 1
                txtEditorName.TabIndex = 2
                txtEditorWebsite.TabIndex = 3
                txtEditorDescription.TabIndex = 4
                txtEditorUsername.TabIndex = 5
                txtEditorPassword.TabIndex = 7
                txtEditorConfirmPassword.TabIndex = 8

                cmdEditorSave.TabIndex = 12
                cmdEditorCancel.TabIndex = 13


                cmdMiniClosePasswordEditor.TabStop = True
                cmdMiniClosePasswordEditor.TabIndex = 14

                Me.txtEditorName.Focus()

                'setup default enter button
                Me.AcceptButton = Me.cmdEditorSave

            Case "Settings"

                'form visibility
                GroupBoxSettings.Location = New System.Drawing.Point(0, 0)
                GroupBoxSettings.Visible = True
                GroupBoxSettings.BringToFront()
                GroupBoxSettings.Size = New Size(473, 528)
                GroupBoxSettings.Enabled = True

                'turn tab stop off for everything visible
                Call DisableTab(Me)

                'settings and preferences.tabstop = True
                ChkBoxAutoLockTimeout.TabStop = True
                ChkBoxAutoLockMinimise.TabStop = True
                chkBoxTips.TabStop = True

                ChkBoxAutoLockTimeout.TabIndex = 1
                ChkBoxAutoLockMinimise.TabIndex = 2
                chkBoxTips.TabIndex = 3

                'master username and password
                txtSettingsUsername.TabStop = True
                txtSettingsPassword.TabStop = True
                txtSettingsPasswordConfirm.TabStop = True
                txtSettingsPasswordReminder.TabStop = True

                txtSettingsUsername.TabIndex = 4
                txtSettingsPassword.TabIndex = 5
                txtSettingsPasswordConfirm.TabIndex = 6
                txtSettingsPasswordReminder.TabIndex = 7


                cmdSettingsSave.TabIndex = 10
                cmdSettingsCancel.TabIndex = 11


                cmdMiniCloseSettings.TabStop = True

                cmdMiniCloseSettings.TabIndex = 12

                'setup default enter button
                Me.AcceptButton = cmdSettingsSave

            Case "CategoryEditor"

                'form visibility
                GroupBoxCategoryEditor.Location = New System.Drawing.Point(0, 0)
                GroupBoxCategoryEditor.Visible = True
                GroupBoxCategoryEditor.BringToFront()
                GroupBoxCategoryEditor.Size = New Size(473, 528)
                GroupBoxCategoryEditor.Enabled = True

                'turn tab stop off for everything visible
                Call DisableTab(Me)

                'do tab order here
                cboCategoryEditorCategory.TabStop = True
                cmdCategoryEditorAdd.TabStop = True
                cmdCategoryEditorRename.TabStop = True
                cmdCategoryEditorDelete.TabStop = True
                txtCategoryEditorCategoryName.TabStop = True
                txtField1Name.TabStop = True
                txtField2Name.TabStop = True
                txtField3Name.TabStop = True
                txtField4Name.TabStop = True
                cmdCategoryEditorSave.TabStop = True
                cmdCategoryEditorClose.TabStop = True

                cboCategoryEditorCategory.TabIndex = 1
                cmdCategoryEditorAdd.TabIndex = 2
                cmdCategoryEditorRename.TabIndex = 3
                cmdCategoryEditorDelete.TabIndex = 4
                txtCategoryEditorCategoryName.TabIndex = 5
                txtField1Name.TabIndex = 6
                txtField2Name.TabIndex = 7
                txtField3Name.TabIndex = 8
                txtField4Name.TabIndex = 9
                cmdCategoryEditorSave.TabIndex = 10
                cmdCategoryEditorClose.TabIndex = 11



            Case Else
                Call MsgBox("Invalid Screen : " & ScreenType)
        End Select
    End Sub




    Private Sub cmdOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Call MsgBox("open")

    End Sub


    Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub




    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        If Me.ChkBoxAutoLockTimeout.Checked = True Then



            Call LockScreen()

            Me.Timer1.Enabled = False

            Me.NotifyIcon1.BalloonTipText = "Formition Password Safe Locked Automatically."
            Me.NotifyIcon1.ShowBalloonTip(3000)

            WindowState = FormWindowState.Minimized
            Toolbox.Visible = False

            'set default enter key
            Me.AcceptButton = cmdLogin
        End If

    End Sub

    Private Sub LockScreen()
        Call SetupScreen("Login")
    End Sub
    Private Sub cmdNewUser_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles cmdNewUser.LinkClicked
        Call SetupScreen("Registration")
        Call Tip("Important Tip", "This is where you will create your new master username and password - hopefully the only one you will need to remember from now on. Make it secure, so not even your best friend can guess your password and you need to make sure you don't forget it; you can change this later if you can't think of a good one now.")
    End Sub



    Private Sub Login(ByVal Username, ByVal Password)

        
        Common.ToggleLocked = False


        If Len(Username) = 0 Or Len(Password) = 0 Then
            Call Message("Incorrect Login", "Your username or password cannot be blank")
            Exit Sub
        End If

        'check log in here
        If Not Common.Login(Username, Password) Then
            Call Message("Login Failed", "Incorrect Username or Password.")
            Exit Sub
        End If

        ' store userid and password for future encryption
        Common.EncryptedUserid = Encrypt(Common.UserKey, Me.txtMasterUsername.Text)
        Common.EncryptedUserid = Encrypt(Common.UserKey, Me.txtMasterPassword.Text)

        Me.GroupBoxLogin.Visible = False
        Me.GroupBoxRegistration.Visible = False
        Me.Timer1.Enabled = True

        Call Status("Logged in successfully")

        Call SetupScreen("MainScreen")



        'clear the master password now
        Me.txtMasterPassword.Text = ""

    End Sub

    Private Sub cmdRegistrationCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdRegistrationCancel.Click
        Call SetupScreen("Login")
    End Sub




    Public Sub Message(ByVal Header As String, ByVal Message As String, Optional ByVal ImageType As String = "Warning", Optional ByVal x As Integer = 88, Optional ByVal y As Integer = 139)

        DisableAllSubFields()

        

        If PanelMessage.Visible = True Then
            'message already displayed, so add another
            NumberOfMessages = NumberOfMessages + 1
            ReDim Preserve Messages(NumberOfMessages)
            ReDim Preserve Headers(NumberOfMessages)
            ReDim Preserve MessageType(NumberOfMessages)
            Messages(NumberOfMessages - 1) = Message
            Headers(NumberOfMessages - 1) = Header
            MessageType(NumberOfMessages - 1) = ImageType

        Else
            Me.lblMessageBody.Text = Message
            Me.lblMessageHeader.Text = Header

            'Toolbox
            Toolbox.lblMessage.Text = Message
            Toolbox.cmdStatusOk.Visible = True
            Toolbox.lblMessage.Visible = True

            Select Case ImageType
                Case "Warning"
                    ImgTickforMessage.Visible = False
                    ImgCautionForMessage.Visible = True
                    ImgMessageHeaderColour.BackColor = Color.OrangeRed
                    lblMessageHeader.BackColor = Color.OrangeRed

                    'ToolBox
                    Toolbox.ImgWarningMessage.Visible = True
                    Toolbox.ImgOkMessage.Visible = False
                    Toolbox.PictureBoxStatus.Visible = False

                Case "Info"
                    ImgTickforMessage.Visible = True
                    ImgCautionForMessage.Visible = False
                    ImgMessageHeaderColour.BackColor = Color.LimeGreen
                    lblMessageHeader.BackColor = Color.LimeGreen

                    'ToolBox
                    Toolbox.ImgWarningMessage.Visible = False
                    Toolbox.PictureBoxStatus.Visible = False
                    Toolbox.ImgOkMessage.Visible = True
            End Select
        End If

        Me.PanelMessage.Visible = True
        Me.PanelMessage.Location = New System.Drawing.Point(x, y)



        Me.PanelMessage.BringToFront()


    End Sub

    Public Sub NextMessage()

        Dim ImageType As String = ""
        If NumberOfMessages > 0 Then

            Me.lblMessageHeader.Text = Headers(NumberOfMessages - 1)
            Me.lblMessageBody.Text = Messages(NumberOfMessages - 1)

            'Toolbox
            Toolbox.lblMessage.Text = Messages(NumberOfMessages - 1)


            ImageType = MessageType(NumberOfMessages - 1)

            'delete this message
            Headers(Headers.Length - 1) = Nothing
            Messages(Messages.Length - 1) = Nothing
            MessageType(MessageType.Length - 1) = Nothing

            NumberOfMessages = NumberOfMessages - 1

            Select Case ImageType
                Case "Warning"
                    ImgTickforMessage.Visible = False
                    ImgCautionForMessage.Visible = True
                    ImgMessageHeaderColour.BackColor = Color.OrangeRed
                    lblMessageHeader.BackColor = Color.OrangeRed

                    'ToolBox
                    Toolbox.ImgWarningMessage.Visible = True
                    Toolbox.PictureBoxStatus.Visible = False
                    Toolbox.ImgOkMessage.Visible = False

                Case "Info"
                    ImgTickforMessage.Visible = True
                    ImgCautionForMessage.Visible = False
                    ImgMessageHeaderColour.BackColor = Color.LimeGreen
                    lblMessageHeader.BackColor = Color.LimeGreen

                    'ToolBox
                    Toolbox.ImgWarningMessage.Visible = False
                    Toolbox.PictureBoxStatus.Visible = False
                    Toolbox.ImgOkMessage.Visible = True

            End Select

        Else
            Me.PanelMessage.Visible = False
            Toolbox.cmdStatusOk.Visible = False
            Toolbox.ImgOkMessage.Visible = False
            Toolbox.ImgWarningMessage.Visible = False
            Toolbox.lblMessage.Visible = False            
            EnableAllSubFields()
        End If

    End Sub

    Private Sub cmdMessageClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdMessageClose.Click
        NextMessage()
    End Sub

    Private Sub cmdRegister_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdRegister.Click

        Me.PanelTip.Visible = False

        If Not Me.txtNewPassword1.Text.ToString = Me.txtNewPassword2.Text.ToString Then
            Call Message("Registration Error", "Your password and confirmation password must match.")
            Exit Sub
        End If

        If chkTermsConditions.Checked = False Or chkIAgree.Checked = False Then
            Call Message("Registration Error", "You must check the two boxes that you understand the importance of your master password and that you understand the terms and conditions of using this software.")
            Exit Sub
        End If


        'check to make sure this username does not already exist in the local dbase
        If Common.CheckUserExists(Me.txtNewUsername.Text) Then
            Call Message("Registration Error", "The username you have selected already exists on this local computer, please choose another to continue.")
            Exit Sub
        End If

        'insert data into the dbase
        If Common.RegisterUser(Me.txtNewUsername.Text, Me.txtNewPassword1.Text, Me.txtPasswordReminder.Text) Then
            Call Login(Me.txtNewUsername.Text, Me.txtNewPassword1.Text)
        End If

    End Sub

    Dim Tips As String()
    Dim TipHeaders As String()
    Dim TipMessages As Integer = 0

    Public Sub Tip(ByVal Header As String, ByVal TipMessage As String, Optional ByVal ImageType As String = "Warning", Optional ByVal x As Integer = 88, Optional ByVal y As Integer = 139)

        If Me.chkBoxTips.Checked = True Then
            Exit Sub
        End If

        DisableAllSubFields()

        If Common.Userid = Nothing Then
            Me.CheckBoxTipMessages.Visible = False
        Else
            Me.CheckBoxTipMessages.Visible = True
        End If

        If PanelTip.Visible = True Then
            TipMessages = TipMessages + 1
            ReDim Preserve Tips(TipMessages)
            ReDim Preserve TipHeaders(TipMessages)
            Tips(TipMessages - 1) = TipMessage
            TipHeaders(TipMessages - 1) = Header
        Else
            Me.PanelTip.Visible = True
            Me.PanelTip.Location = New System.Drawing.Point(x, y)
            PanelTip.BringToFront()
            Me.txtTip.Text = TipMessage
            Me.lblTipHeader.Text = Header
        End If


    End Sub



    Public Sub Status(ByVal Message As String)
        Me.PictureBoxStatus.Visible = True
        Me.lblStatus.Visible = True
        Me.lblStatus.Text = Message

        Toolbox.lblStatus.Text = Message
        Toolbox.lblStatus.Visible = True
        Toolbox.PictureBoxStatus.Visible = True
    End Sub

    Private Sub StatusClear()
        Me.PictureBoxStatus.Visible = False


        Toolbox.lblStatus.Visible = True
        Toolbox.PictureBoxStatus.Visible = True
    End Sub

    



    Private Sub cmdNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdNew.Click

        Call Common.NewPassword()
    End Sub

 



    Private Sub displayEditorPassword()
        If Me.txtEditorPassword.PasswordChar = "*" Then
            Me.txtEditorPassword.PasswordChar = ""
            Me.txtEditorConfirmPassword.PasswordChar = ""
            Me.cmdEditorDisplayPassword.Text = "Hide Password"
        Else
            Me.txtEditorPassword.PasswordChar = "*"
            Me.txtEditorConfirmPassword.PasswordChar = "*"
            Me.cmdEditorDisplayPassword.Text = "Display Password"
        End If
    End Sub

    Private Sub cmdEditorRandomlyCreatePasswordChar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdEditorRandomlyCreatePasswordChar.Click
        'make sure the user see's what they are doing here.
        If Me.txtEditorPassword.PasswordChar = "*" Then
            Call displayEditorPassword()
        End If
        Me.txtEditorPassword.Text = Me.txtEditorPassword.Text & RandomChar()
        Me.txtEditorConfirmPassword.Text = Me.txtEditorPassword.Text
    End Sub

    Private Sub cmdEditorDisplayPassword_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdEditorDisplayPassword.Click
        Call displayEditorPassword()
    End Sub

    Private Sub cmdEditorCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdEditorCancel.Click
        Me.SetupScreen("MainScreen")
        Me.Status("Cancelled password editor changes.")
    End Sub

    Private Sub cmdEditorSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdEditorSave.Click

        Try
            If Len(Me.cboEditorCategory.SelectedValue.ToString) = 0 Then                
                Call Message("Saving Password", "Please select a category for this password.")
                Exit Sub
            End If
        Catch ex As Exception
            Call Message("Saving Password", "Please select a category for this password.")
            Exit Sub
        End Try
        

        If Me.txtEditorConfirmPassword.Text <> Me.txtEditorPassword.Text Then
            Call Message("Unable to Save", "The password and the confirm password do not match, please correct.")
            Exit Sub
        End If


        If CurrentlySelectedPasswordID <> Nothing Then
            'Update
            Common.PasswordEdit(CurrentlySelectedPasswordID, Userid.ToString, Me.txtEditorName.Text, Me.txtEditorDescription.Text, Me.txtEditorWebsite.Text, Me.txtEditorUsername.Text, Me.txtEditorPassword.Text, Common.SkipField, Me.cboEditorCategory.SelectedValue.ToString, Me.SecurityControlPasswordEditor.GetLevel, Common.GetDate)
        Else
            'Save New
            Common.PasswordEdit(SkipField, Userid.ToString, Me.txtEditorName.Text, Me.txtEditorDescription.Text, Me.txtEditorWebsite.Text, Me.txtEditorUsername.Text, Me.txtEditorPassword.Text, Common.GetDate, Me.cboEditorCategory.SelectedValue.ToString, Me.SecurityControlPasswordEditor.GetLevel, Common.GetDate)
        End If


        Me.SetupScreen("MainScreen")
        Me.Status("Password saved.")


    End Sub

    Private Sub ToolStripMenuItem_NewAccount_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem_NewAccount.Click
        Call NewPassword()
    End Sub



    Private Sub cmdLockPasswords_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdLockPasswords.Click

        If ToggleLocked = True Then
            ToggleLocked = False
        Else
            ToggleLocked = True
        End If

        PopulatePasswordList(Me.cboEditorCategory.SelectedValue, ToggleLocked)
    End Sub





    Private Sub cmdDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDelete.Click

        Call Common.DeletePassword(Common.CurrentlySelectedPasswordID)
        CurrentlySelectedPasswordID = Nothing
        Call PasswordRowSelected()

    End Sub


    Private Sub txtEditorPassword_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtEditorPassword.TextChanged

  
        SecurityControlPasswordEditor.SetLevel(Common.CheckPasswordStrength(Me.txtEditorPassword.Text))
  
        If Me.txtEditorPassword.Text = Me.txtEditorConfirmPassword.Text Then
            lblEditorMatch.Text = "Match"
        Else
            lblEditorMatch.Text = ""
        End If
    End Sub

    Private Sub cmdCopyUserid_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCopyUserid.Click
        Call Common.CopyUseridToClipBoard(Common.CurrentlySelectedPasswordID)
    End Sub

    Private Sub cmdLaunchWeblink_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdLaunchWeblink.Click
        Call Common.LaunchInBrowser(Common.CurrentlySelectedPasswordID)
    End Sub


    Private Sub cmdSettings_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSettings.Click
        Call SetupScreen("Settings")
    End Sub


    Private Sub txtNewPassword1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtNewPassword1.TextChanged

        If Len(txtNewUsername.Text) > 0 Then            
            SecurityControlRegistration.SetLevel(Common.CheckPasswordStrength(Me.txtNewPassword1.Text, txtNewUsername.Text))
        End If

        If txtNewPassword2.Text = txtNewPassword1.Text Then
            lblNewPasswordMatch.Text = "Match"
        Else
            lblNewPasswordMatch.Text = ""
        End If

    End Sub

    Private Sub txtNewPassword2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtNewPassword2.TextChanged
        If txtNewPassword2.Text = txtNewPassword1.Text Then
            lblNewPasswordMatch.Text = "Match"
        Else
            lblNewPasswordMatch.Text = ""
        End If
    End Sub




    Private Sub cmdTipClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdTipClose.Click

        'If the user does not want to see tips again.
        'Set this preferences on the preference screen and save it for future messages.
        If Me.CheckBoxTipMessages.Checked Then
            Me.chkBoxTips.Checked = True
            UpdateBasicPreferences()
        End If

        If TipMessages > 0 Then
            Me.txtTip.Text = Tips(TipMessages - 1)
            Me.lblTipHeader.Text = TipHeaders(TipMessages - 1)
            TipMessages = TipMessages - 1
        Else
            Me.PanelTip.Visible = False
            EnableAllSubFields()
        End If

    End Sub

    Private Sub cmdSettingsCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSettingsCancel.Click
        Call SetupScreen("MainScreen")
    End Sub

    Private Sub cmdFormitionRegoCheck_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Call Tip("Under Construction...", "This feature has not been implemented yet, it will be up and running March to April 2011, register on Formition.com for information on when this will be available.")
    End Sub

    Private Sub cmdSettingsSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSettingsSave.Click
        Call Common.PreferencesSave()
    End Sub

    Private Sub cmdCategoryEditor_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCategoryEditor.Click
        Call Common.CategoryEditorLoad()

    End Sub

    Private Sub cmdCategoryEditorAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdCategoryEditorAdd.Click

        txtCategoryEditorCategoryName.Visible = True
        chkCategoryEditorShowAdvancedOptions.Visible = True

        cmdCategoryEditorSave.Visible = True

        lblCategoryName.Visible = True


        txtCategoryEditorCategoryName.Text = ""
        chkCategoryEditorCreateNew.Checked = True
        txtField1Name.Text = "Name"
        txtField2Name.Text = "Website"
        txtField3Name.Text = "Description"
        txtField4Name.Text = "User name"

    End Sub

    Private Sub cmdCategoryEditorDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCategoryEditorDelete.Click

        Dim Answer As String = MsgBox("Are you sure you want to delete this category and all the associated passwords permanently?", MsgBoxStyle.OkCancel, "Formition Password Safe")

        If Answer = 1 Then
            Call Common.CategoryDelete(Me.cboCategoryEditorCategory.SelectedValue)
        End If

        'refresh category list (on all screens)
        Call Common.RefreshCategoryEditorCategoryList()
        Call Common.PopulateCategories()
    End Sub

    Private Sub cmdCategoryEditorRename_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCategoryEditorRename.Click


        chkCategoryEditorCreateNew.Checked = False
        Me.chkCategoryEditorShowAdvancedOptions.Visible = True
        txtCategoryEditorCategoryName.Visible = True
       
        cmdCategoryEditorSave.Visible = True

        lblCategoryName.Visible = True

        Dim dsCategory As New DataSet
        dsCategory = Common.CategorySearchByID(cboCategoryEditorCategory.SelectedValue)

        lblSettingsCategoryEditorCategoryID.Text = cboCategoryEditorCategory.SelectedValue.ToString
        Me.txtCategoryEditorCategoryName.Text = dsCategory.Tables(0).Rows(0).Item("Name")
        txtField1Name.Text = dsCategory.Tables(0).Rows(0).Item("Field1Name")
        txtField2Name.Text = dsCategory.Tables(0).Rows(0).Item("Field2Name")
        txtField3Name.Text = dsCategory.Tables(0).Rows(0).Item("Field3Name")
        txtField4Name.Text = dsCategory.Tables(0).Rows(0).Item("Field4Name")


    End Sub



    Private Sub cmdCopyPassword_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCopyPassword.Click
        Call PasswordRowSelected()
        Common.CopyPasswordtoClipboard(Common.CurrentlySelectedPasswordID)

    End Sub

    Private Sub ToolStripMenuItem_CopyPassword_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem_CopyPassword.Click
        Call PasswordRowSelected()
        Common.CopyPasswordtoClipboard(Common.CurrentlySelectedPasswordID)
    End Sub

    Private Sub ToolStripMenuItem_CopyUserid_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem_CopyUserid.Click
        Call PasswordRowSelected()
        Call Common.CopyUseridToClipBoard(Common.CurrentlySelectedPasswordID)
    End Sub

    Private Sub LaunchInBrowserToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LaunchInBrowserToolStripMenuItem.Click
        Call Common.LaunchInBrowser(Common.CurrentlySelectedPasswordID)
    End Sub

    Private Sub ShowPasswordToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ShowPasswordToolStripMenuItem.Click
        Call SetupScreen("Settings")
    End Sub

    Private Sub ToolStripMenuItem_Edit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem_Edit.Click
        Call PasswordRowSelected()
        Call PasswordSelected(Common.CurrentlySelectedPasswordID)
    End Sub


    Private Sub ToolStripMenuItem_Delete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem_Delete.Click
        Call PasswordRowSelected()
        Call Common.DeletePassword(Common.CurrentlySelectedPasswordID)
    End Sub




    Private Sub cmdSearchGo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSearchGo.Click
        Call Common.Search(Me.txtSearch.Text, Common.ToggleLocked)
    End Sub


    Private Sub cboCategory_SelectionChangeCommitted(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboCategory.SelectionChangeCommitted


        If Not BackgroundDataLoadingIgnoreEvents Then


            Common.CurrentlySelectedPasswordID = Nothing
            Common.CurrentlySelectedUserCategory = Nothing

            'Call Common.PopulatePasswordList(Me.cboCategory.SelectedValue, Common.ToggleLocked)
            If Me.cboCategory.Items.Count = 0 Then
                Exit Sub
            End If

            If Not IsDBNull(cboCategory.SelectedValue) Then
                Common.CurrentlySelectedUserCategory = cboCategory.SelectedValue
                PopulatePasswordList(Common.CurrentlySelectedUserCategory, Common.ToggleLocked)
                PasswordRowSelected(True)
            Else
                Call Search(Me.txtSearch.Text, ToggleLocked)
            End If

        End If

    End Sub

    Private Sub cmdMiniClosePasswordEditor_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdMiniClosePasswordEditor.Click
        Call ExitScreenCode("Editor")
    End Sub


    Private Sub cmdMiniCloseSettings_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdMiniCloseSettings.Click
        Call ExitScreenCode("Settings")
    End Sub

    Private Sub cmdMiniCloseRegistration_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdMiniCloseRegistration.Click
        Call ExitScreenCode("Registration")
    End Sub

    Private Sub cmdMiniCloseCategoryEditor_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdMiniCloseCategoryEditor.Click
        Call ExitScreenCode("CategoryEditor")
    End Sub

    Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
        Call Common.LogOff()
        Me.EnableAllSubFields()
        Toolbox.Close()
    End Sub

    Private Sub cmdForgotPassword_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles cmdForgotPassword.LinkClicked
        Call Common.PasswordReminder(Me.txtMasterUsername.Text)
    End Sub

    Private Sub cmdLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdLogin.Click

        Call Login(Me.txtMasterUsername.Text, Me.txtMasterPassword.Text)



    End Sub


    Private Sub cmdCategoryEditorClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCategoryEditorClose.Click

        If Me.chkCategoryEditorReturnToPasswordEditor.Checked Then

            If IsNothing(Common.CurrentlySelectedPasswordID) Then
                Common.PasswordSelected(Common.CurrentlySelectedPasswordID)
            Else
                'just go back to the editor, they were creating a new password
                Call SetupScreen("Editor")
            End If



        Else
            Call SetupScreen("MainScreen")
        End If

        Call Status("Category Editor Closed")
    End Sub




    Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Click

        Call Common.LaunchToFormition()

    End Sub

   

    Private Sub Label32_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Call Common.LaunchToFormition()
    End Sub



    Private Sub txtEditorDescription_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtEditorDescription.GotFocus
        'disable default enter key kere
        Me.AcceptButton = Nothing
    End Sub

    Private Sub txtEditorDescription_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtEditorDescription.LostFocus
        'ensable default enter key kere
        Me.AcceptButton = Me.cmdEditorSave
    End Sub





    Private Sub DataGridPasswords_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridPasswords.DoubleClick

        Try
            If Len(sender.SelectedRows.Item(0).Cells(0).Value.ToString) > 0 Then
                Call Common.PasswordRowSelected()
                Call PasswordSelected(sender.SelectedRows.Item(0).Cells(0).Value)
            End If
        Catch ex As Exception

        End Try
    End Sub


    Private Sub DataGridPasswords_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles DataGridPasswords.KeyPress

        'need to research how to stop datagrid advancing on enter?

        If Chr(13).ToString = e.KeyChar.ToString Then

            Call Common.PasswordRowSelected()
            Call Common.PasswordSelected(Common.CurrentlySelectedPasswordID)

        End If



    End Sub




    Private Sub txtEditorConfirmPassword_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtEditorConfirmPassword.TextChanged

        Call Me.SecurityControlPasswordEditor.SetLevel(Common.CheckPasswordStrength(Me.txtEditorPassword.Text))

        If Me.txtEditorPassword.Text = Me.txtEditorConfirmPassword.Text Then
            lblEditorMatch.Text = "Match"
        Else
            lblEditorMatch.Text = ""
        End If
    End Sub

    Private Sub txtSettingsPassword_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSettingsPassword.TextChanged
        SecurityControlSettings.SetLevel(Common.CheckPasswordStrength(Me.txtSettingsPassword.Text))

        If Me.txtSettingsPassword.Text = Me.txtSettingsPasswordConfirm.Text Then
            lblSettingsMatch.Text = "Match"
        Else
            lblSettingsMatch.Text = ""
        End If
    End Sub

    Private Sub txtSettingsPasswordConfirm_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSettingsPasswordConfirm.TextChanged
        SecurityControlSettings.SetLevel(Common.CheckPasswordStrength(Me.txtSettingsPassword.Text))

        If Me.txtSettingsPassword.Text = Me.txtSettingsPasswordConfirm.Text Then
            lblSettingsMatch.Text = "Match"
        Else
            lblSettingsMatch.Text = ""
        End If
    End Sub


    Private Sub txtCategoryEditorCategoryName_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtCategoryEditorCategoryName.GotFocus
        Me.AcceptButton = cmdCategoryEditorAdd
    End Sub

    Private Sub txtCatgegoryEditorCategoryRename_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs)
        Me.AcceptButton = cmdCategoryEditorRename
    End Sub

    Private Sub DataGridPasswords_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridPasswords.Click
        Common.PasswordRowSelected()
    End Sub

    Private Sub DataGridPasswords_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridPasswords.SelectionChanged

        'Call PasswordRowSelected(False)

    End Sub

    Private Sub ShowUsernameToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ShowUsernameToolStripMenuItem.Click
        If ToggleLocked = True Then
            ToggleLocked = False
        Else
            ToggleLocked = True
        End If

        PopulatePasswordList(Me.cboEditorCategory.SelectedValue, ToggleLocked)

    End Sub




  
   
    Private Sub cmdMiniCloseRestore_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdMiniCloseRestore.Click
        Call ExitScreenCode("Restore")
    End Sub

    Private Sub cmdRestoreCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdRestoreCancel.Click
        Call Me.SetupScreen("MainScreen")
    End Sub

    Private Sub cmdRestoreSystem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdRestoreSystem.Click
        Dim result As Integer
        result = MsgBox("Are you sure you want to restore this environment from a backup stored on formition.com?", MsgBoxStyle.YesNo)
        If result = 1 Then

            'perform restore of database here.

            'now login and report that restoration has been completed successfully.

        Else
            Call Me.SetupScreen("MainScreen")
            Me.Status("Cancelled Restore")
        End If
    End Sub

    Private Sub LinkLabel2_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs)
        Call Common.LaunchToFormition()
    End Sub

   
    Private Sub cmdBackupDatabase_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdBackupDatabase.Click
        Me.DatabaseBackupDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal)
        DatabaseBackupDialog.ShowDialog()
    End Sub

    
    Private Sub cmdUpgrade_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdUpgrade.Click
        Call UpgradeSoftwareVersion()
    End Sub

    Private Sub DatabaseBackupDialog_FileOk(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles DatabaseBackupDialog.FileOk


        'pause 10 seconds or whatever the database buffer is?
        Call Common.backup(Me.DatabaseBackupDialog.FileName)


    End Sub

    
    Private Sub cmdRestore_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdRestore.Click
        Me.RestoreDatabaseDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal)

        Me.RestoreDatabaseDialog.ShowDialog()
    End Sub


    Private Sub RestoreDatabaseDialog_FileOk(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles RestoreDatabaseDialog.FileOk
        'pause 10 seconds or whatever the database buffer is?


        Call Common.restore(Me.RestoreDatabaseDialog.FileName)

      
    End Sub

    Private Sub LinkLabel3_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel3.LinkClicked
        'open up the terms and conditions
        Dim results As String
        Dim Path As String = Environ("windir") & "\explorer.exe " & Common.DoubleQuote & Common.ApplicationInstallPath & "\Documents\terms and conditions.rtf" & Common.DoubleQuote
        results = Shell(Path)
    End Sub

   
    Private Sub txtNewUsername_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtNewUsername.TextChanged
        If Len(txtNewPassword1.Text) > 0 Then
            SecurityControlRegistration.SetLevel(Common.CheckPasswordStrength(Me.txtNewPassword1.Text, txtNewUsername.Text))
        End If
    End Sub

   
    Private Sub cmdCategoryEditorSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCategoryEditorSave.Click


        '------------------------------
        'make sure no two column names are the same
        Dim samesame As Boolean = False

        Select Case Me.txtField1Name.Text
            Case Me.txtField2Name.Text : samesame = True
            Case Me.txtField3Name.Text : samesame = True
            Case Me.txtField4Name.Text : samesame = True
        End Select
        Select Case Me.txtField2Name.Text
            Case Me.txtField1Name.Text : samesame = True
            Case Me.txtField3Name.Text : samesame = True
            Case Me.txtField4Name.Text : samesame = True
        End Select
        Select Case Me.txtField3Name.Text
            Case Me.txtField2Name.Text : samesame = True
            Case Me.txtField1Name.Text : samesame = True
            Case Me.txtField4Name.Text : samesame = True
        End Select
        Select Case Me.txtField4Name.Text
            Case Me.txtField2Name.Text : samesame = True
            Case Me.txtField3Name.Text : samesame = True
            Case Me.txtField1Name.Text : samesame = True
        End Select

        If samesame Then
            Call Me.Message("Error Saving Category", "No two field names can be the same as they will not display properly in the main window.")
            Exit Sub
        End If
        '------------------------------




        'make sure category is not blank
        If Len(txtCategoryEditorCategoryName.Text) = 0 Then
            Call Message("Error saving category", "The category name must not be blank.")
            Exit Sub
        End If

        'make sure the category name does not already exist
        If chkCategoryEditorCreateNew.Checked = True Then
            Dim x As Integer = 0
            For x = 0 To cboCategoryEditorCategory.Items.Count - 1
                If UCase(Me.txtCategoryEditorCategoryName.Text) = UCase(cboCategoryEditorCategory.Items(x).ToString) Then
                    Call Message("Error saving category", "The category name already exists, you cannot have two categories with the same name.")
                    Exit Sub
                End If
            Next
            Call Common.CategoryEdit(Common.SkipField, Me.txtCategoryEditorCategoryName.Text, 0, Common.Userid, Me.txtField1Name.Text, Me.txtField2Name.Text, Me.txtField3Name.Text, Me.txtField4Name.Text)
        Else
            'save existing categoryID
            Call Common.CategoryEdit(Me.lblSettingsCategoryEditorCategoryID.Text, Me.txtCategoryEditorCategoryName.Text, 0, Common.Userid, Me.txtField1Name.Text, Me.txtField2Name.Text, Me.txtField3Name.Text, Me.txtField4Name.Text)

        End If



        'refresh category list (on all screens)
        Call Common.RefreshCategoryEditorCategoryList()
        Call Common.PopulateCategories()

        'hide all
        txtCategoryEditorCategoryName.Visible = False
        txtField1Name.Visible = False
        txtField2Name.Visible = False
        txtField3Name.Visible = False
        txtField4Name.Visible = False
        cmdCategoryEditorSave.Visible = False

        chkCategoryEditorShowAdvancedOptions.Visible = False

        lblCategoryName.Visible = False
        lblField1Text.Visible = False
        lblField2Text.Visible = False
        lblField3Text.Visible = False
        lblField4Text.Visible = False
    End Sub

   
    Private Sub cboEditorCategory_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboEditorCategory.SelectedIndexChanged

        If Not Common.BackgroundDataLoadingIgnoreEvents Then

            If cboEditorCategory.Items.Count = 0 Then
                Exit Sub
            End If


            Try
                'adjust category field names
                Dim ds As DataSet
                ds = CategorySearchByID(cboEditorCategory.SelectedValue.ToString)
                lblEditorField1.Text = ds.Tables(0).Rows(0).Item("Field1Name")
                lblEditorField2.Text = ds.Tables(0).Rows(0).Item("Field2Name")
                lblEditorField3.Text = ds.Tables(0).Rows(0).Item("Field3Name")
                lblEditorField4.Text = ds.Tables(0).Rows(0).Item("Field4Name")
            Catch ex As Exception

            End Try

        End If

    End Sub

    Private Sub cmdEditCategoriesFromPasswordEditor_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdEditCategoriesFromPasswordEditor.Click
        Call Common.CategoryEditorLoad(True)
    End Sub

   
    
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


        Dim result As String
        result = MsgBox("Are you sure you want to completely delete this user account? This cannot be undone and is permanent.", MsgBoxStyle.OkCancel, "Formition Password Safe")
        If result = 1 Then
            Call Common.DeleteTestUser(Common.Userid)
            Call SetupScreen("Login")
            Call Tip("Account Deleted", "The account has been permanently deleted", "Info")
        End If
    End Sub

    Private Sub LaunchToolboxToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LaunchToolboxToolStripMenuItem.Click
        Call Common.launchToolbox()
    End Sub

    Private Sub cmdOpenToolbox_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdOpenToolbox.Click
        Call Common.LaunchToolbox()

    End Sub

    Private Sub chkCategoryEditorShowAdvancedOptions_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkCategoryEditorShowAdvancedOptions.CheckedChanged


        If chkCategoryEditorShowAdvancedOptions.Checked Then
            txtField1Name.Visible = True
            txtField2Name.Visible = True
            txtField3Name.Visible = True
            txtField4Name.Visible = True
            lblField1Text.Visible = True
            lblField2Text.Visible = True
            lblField3Text.Visible = True
            lblField4Text.Visible = True
        Else
            txtField1Name.Visible = False
            txtField2Name.Visible = False
            txtField3Name.Visible = False
            txtField4Name.Visible = False
            lblField1Text.Visible = False
            lblField2Text.Visible = False
            lblField3Text.Visible = False
            lblField4Text.Visible = False
        End If
    End Sub

   

    
    Private Sub ToolStripComboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripComboBox1.SelectedIndexChanged

  

        If ToolStripComboBox1.Items.Count <= 1 Then
            Exit Sub
        End If

        'clear the search string
        Call Search(ToolStripComboBox1.Text, True)

        'otherwise user has selected a password and we are not locked down.

        'get the index number which is relative to the actual datagrid currently being displayed.

        Dim findindex As Integer = 0
        Dim found As Boolean = False
        'find the first name in the datagrid that matches this name
        For findindex = 0 To DataGridPasswords.Rows.Count - 1
            'Call MsgBox(ToolStripComboBox1.SelectedText.ToString & " = " & DataGridPasswords.Rows(findindex).Cells(1).Value.ToString)
            If ToolStripComboBox1.SelectedItem.ToString = DataGridPasswords.Rows(findindex).Cells(1).Value.ToString Then
                DataGridPasswords.Rows(findindex).Selected = True
                found = True
                Exit For
            End If
        Next

        'otherwise do nothing.
        If found Then
            Common.PasswordRowSelected()
            Call Common.LaunchToolbox()
        End If
        
    End Sub

    
    Private Sub ToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem1.Click
        'open the password editor (maximise)
        WindowState = FormWindowState.Minimized
        WindowState = FormWindowState.Normal

    End Sub

    Private Sub ToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem2.Click
        Common.LogOff()
        Me.Close()
    End Sub

    Private Sub AddNewPasswordToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddNewPasswordToolStripMenuItem.Click
        Call Common.NewPassword()
        Me.WindowState = FormWindowState.Normal
    End Sub



    Private Sub NotifyIcon1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseClick
        If e.Button = Windows.Forms.MouseButtons.Left Then
            WindowState = FormWindowState.Minimized
            WindowState = FormWindowState.Normal
            Me.BringToFront()
            Me.Refresh()
            Me.txtMasterPassword.Focus()
        End If        
    End Sub

   
    Private Sub PictureBox2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox2.Click
        Call Common.LaunchToFormition()
    End Sub

   
    Private Sub lblRegistrationLink_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles lblRegistrationLink.LinkClicked
        Call Common.LaunchToFormition()
    End Sub

    Private Sub cmdAddRegistrationKey_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAddRegistrationKey.Click
        RegisterLater = False
        CheckRegistration()
    End Sub

 
End Class